const express = require('express');
const formidable = require('formidable');
const { resolve } = require('path');
const userModel = require('../db/models/userModel');
const md5 = require('md5');

const router = express.Router();

let readFile = formidable({
    uploadDir: resolve(__dirname, '../public/upload'),
    keepExtensions: true,
    maxFieldsSize: 1024 * 200
})

// 添加用户接口
router.post('/user', (req, res) => {

    // let { username, pwd, profile } = req.body;
    // console.log(username, pwd, profile);

    readFile.parse(req, async(err, fields, files) => {

        let { username, pwd } = fields;
        let { profile } = files;

        let imgUlr = '/upload/' + profile.newFilename;

        try {

            // 查找数据库里有没有相同名字
            let olduser = await userModel.findOne({ username })

            if (olduser) {
                throw '用户名已存在'
            }

            // 提交数据到数据库
            let data = await userModel.create({
                username,
                pwd: md5(pwd),
                profile: imgUlr
            });

            res.json({
                code: 2000,
                data,
                message: "添加成功"
            })
        } catch (err) {
            res.json({
                code: 2002,
                message: "添加失败，原因：" + err
            })
        }
    })
})

// 获取分页用户列表接口
router.get('/user/:page/:limit', async(req, res) => {
    let { page, limit } = req.params;
    // console.log(page, limit);

    let skip = (page - 1) * limit;

    try {
        let data = await userModel.find().skip(skip).limit(limit).exec();

        let count = await userModel.count();
        res.json({
            code: 2000,
            data: {
                users: data,
                total: count
            },
            message: "获取列表成功"
        })
    } catch (err) {
        res.json({
            code: 2002,
            msg: "获取失败，请检查参数是否正确"
        })
    }

})

// 获取用户信息 - 根据id
router.get('/user', async(req, res) => {
    let { id } = req.query;
    try {
        let data = await userModel.findOne({ _id: id });
        res.json({
            code: 2000,
            data,
            message: "获取用户成功"
        })
    } catch (err) {
        res.json({
            code: 2002,
            message: "参数错误"
        })
    }
})

// 更新用户信息 接口
router.put('/user', (req, res) => {

    // 
    readFile.parse(req, async(err, fileds, files) => {
        let { username, _id } = fileds;
        let { profile } = files;

        let imgUrl = '/upload/' + profile.newFilename;

        let data = await userModel.updateOne({ _id }, {
            username,
            profile: imgUrl
        })

        // console.log(data)
        if (!data.modifiedCount) {
            res.json({
                code: 2002,
                message: "修改失败，请检查，是否缺少参数"
            })
        } else {
            res.json({
                code: 2000,
                message: "更新成功"
            })
        }
    })

})

//删除用户接口
router.delete('/user/:id', async(req, res) => {
    let { id } = req.params;

    await userModel.deleteOne({ _id: id })

    res.json({
        code: 2000,
        message: "删除成功"
    })
})

module.exports = router;